export type SuccessResponse<PayloadType> = {
  code: 200;
  ok: true;
  msg: string;
  payload: PayloadType;
  error: null;
};

export type ErrorResponse<ErrorType = Error> = {
  code: Exclude<number, 200>;
  ok: false;
  msg: string;
  payload: null;
  error: ErrorType;
};

export type ResponseType<P = undefined, E = Error> = SuccessResponse<P> | ErrorResponse<E>;
export function Response<T extends Error>(code: Exclude<number, 200>, msg: string, error?: T): ErrorResponse<T>;
export function Response<T>(code: 200, msg: string, payload?: T): SuccessResponse<T>;
export function Response(code: number, msg = '', payload?: any) {
  if (code === 200) {
    return { code, msg, ok: true, payload, error: null };
  }
  return { code, msg, ok: false, payload: null, error: payload ?? new Error(msg) };
}
